package com.crazyhat.crazyhat.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crazyhat.crazyhat.attribute.ClubPositionEnum;
import com.crazyhat.crazyhat.attribute.ClubStatusEnum;
import com.crazyhat.crazyhat.attribute.TokenPayloadEnum;
import com.crazyhat.crazyhat.dto.ClubMemberDTO;
import com.crazyhat.crazyhat.entity.Club;
import com.crazyhat.crazyhat.entity.Participation;
import com.crazyhat.crazyhat.mapper.ClubMapper;
import com.crazyhat.crazyhat.mapper.ParticipationMapper;
import com.crazyhat.crazyhat.service.IParticipationService;
import com.crazyhat.crazyhat.utils.ThreadLocalUtil;
import com.github.yulichang.query.MPJQueryWrapper;

/**
 * <p>
 * 参与的社团 服务实现类
 * </p>
 *
 * @author crazyhat
 * @since 2024-07-05
 */
@Service
public class ParticipationServiceImpl extends ServiceImpl<ParticipationMapper, Participation> implements IParticipationService {

    @Autowired
    ParticipationMapper participationMapper;

    @Autowired
    private ClubMapper clubMapper;

    /**
     * 获取社团管理员列表
     * @param club
     * @return
     */
    public List<Participation> getClubManagerList(Integer clubId){

        if (clubId==null) {
            return null;
        }

        QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
        queryWrapper
            .eq("club_id", clubId)
            .in("club_position", ClubPositionEnum.LEADER,ClubPositionEnum.SECOND_LEADER)
            .select("student_id");

        List<Participation> participationList = participationMapper.selectList(queryWrapper);

        return participationList;
    }

    public Page<Participation> getParticipation(int pageNum, int pageSize){
        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get("studentId");

        QueryWrapper<Club> clubQueryWrapper = new QueryWrapper<>();
        clubQueryWrapper.eq("club_status", ClubStatusEnum.Open)
                .or()
                .eq("club_status",ClubStatusEnum.RestrictJoining);
        List<Club> openClubs = clubMapper.selectList(clubQueryWrapper);
        List<Integer> openClubIds = openClubs.stream().map(Club::getClubId).collect(Collectors.toList());

        if (openClubIds.isEmpty()) {
            return new Page<>(pageNum, pageSize);
        }

        QueryWrapper<Participation> participationQueryWrapper = new QueryWrapper<>();
        participationQueryWrapper.eq("student_id", studentId)
                .in("club_id", openClubIds)
                .orderByDesc("participate_time");

        Page<Participation> page = new Page<>(pageNum, pageSize);

        return participationMapper.selectPage(page, participationQueryWrapper);
    }

    /**
     * 判断用户是否加入社团
     */
    @Override
    public boolean hasParticipation(Integer clubId, Integer studentId) {

        if (clubId==null ||studentId==null) {
            return false;
        }

        QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
        queryWrapper
            .eq("student_id", studentId)
            .eq("club_id", clubId);

        Participation participation= participationMapper.selectOne(queryWrapper);


        if (participation!=null) {
            return true;
        }

        return false;
    }

    /**
     * 获取用户在该社团的职位
     */
    @Override
    public ClubPositionEnum getclubPositionOfUser(Integer clubId) {

        if (clubId==null) {
            return ClubPositionEnum.NONE;
        }

        Map<String,Object> map=ThreadLocalUtil.get();
        Integer studentId=(Integer)map.get(TokenPayloadEnum.StudentId.getValue());

        QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
        queryWrapper
            .eq("student_id", studentId)
            .eq("club_id", clubId);

        Participation participation=participationMapper.selectOne(queryWrapper);

        if (participation==null) {

            //如果无该社团的参与信息
            return ClubPositionEnum.NONE;

        } else {
            return participation.getClubPosition();
        }
    }

    @Override
    public boolean isCommunityManager(Integer clubId) {

        if (clubId==null) {
            return false;
        }

        ClubPositionEnum clubPositionEnum=getclubPositionOfUser(clubId);

        if (clubPositionEnum.equals(ClubPositionEnum.LEADER)
                || clubPositionEnum.equals(ClubPositionEnum.SECOND_LEADER)) {

            //用户为该社团的管理员，即一把手、二把手

            return true;
        }

        return false;
    }

    @Override
    public List<Participation> selectList(QueryWrapper<Participation> queryWrapper) {
        return participationMapper.selectList(queryWrapper);
    }

    @Override
    public void deleteById(Participation participation) {
        participationMapper.deleteById(participation);
    }

    /**
     * 获取某社团的所有成员
     * @param clubId 社团id
     * @return 成员列表
     */
    @Override
    public List<ClubMemberDTO> getClubMemberList(Integer clubId) {

        if (clubId==null) {
            return null;
        }

        Map<String,Object> map=ThreadLocalUtil.get();
        Integer studentId= (Integer) map.get(TokenPayloadEnum.StudentId.getValue());

        if (!(hasParticipation(clubId, studentId))) {
            return null;
        }

        MPJQueryWrapper<Participation> mpjQueryWrapper=new MPJQueryWrapper<>();
        mpjQueryWrapper
            .selectAll(Participation.class)
            .select("u.name","u.avatar_url")
            .leftJoin("user u on u.student_id = t.student_id")
            .eq("t.club_id",clubId);

        List<ClubMemberDTO> clubMemberList=participationMapper.selectJoinList(ClubMemberDTO.class, mpjQueryWrapper);

        return clubMemberList;
    }

}
